﻿using Silk.NET.Maths;
using Silk.NET.OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core;

/// <summary>
/// WIP Only for test
/// </summary>
public class Rdb_TestRenderable
{
    readonly List<Rd_MeshCommon> _meshes = new List<Rd_MeshCommon>();

    public Rd_VertexPrototype VertexPrototype;
    public Rd_Shader Shader;
    public uint Texture1;
    public uint Texture2;
    public Matrix4x4 Transform;
    public void AddMesh(Rd_MeshCommon mesh)
    {
#if DEBUG
        if (mesh.VertexPrototype != VertexPrototype) throw new Exception("Can't add mesh with wrong vertexPrototype");
#endif
        _meshes.Add(mesh);
    }
    
    public void Clear() => _meshes.Clear();

    float i = 0;
    public unsafe void Render(Rd_Context rc)
    {
        // 对目标进行变换
        Transform = Matrix4x4.Identity;
        Transform *= Matrix4x4.CreateRotationZ(i++/180f);
        Transform *= Matrix4x4.CreateScale(1.5f);
        Transform.Translation = new Vector3(0.5f, -0.7f, 0f);

        rc.CurrentVertexPrototype = VertexPrototype; // 绑定VAO

        rc.UseProgram(Shader.ProgramID);

        rc.BindTextureAt(0, Texture1);
        rc.BindTextureAt(1, Texture2);
        rc._gl.Uniform1(rc.GetUniformLocation(Shader.ProgramID, "texture1"), 0);
        rc._gl.Uniform1(rc.GetUniformLocation(Shader.ProgramID, "texture2"), 1);

        Matrix4x4 ccc = Transform;
        rc._gl.UniformMatrix4(rc.GetUniformLocation(Shader.ProgramID, "transform"), 1, false,  (float*)&ccc);


        // 依次渲染
        foreach (var mesh in  _meshes)
        {
            rc.BindBuffer(BufferTargetARB.ElementArrayBuffer, mesh.ElementBuffer);
            rc.BindBuffer(BufferTargetARB.ArrayBuffer, mesh.Buffer);

            unsafe
            {
                rc.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, (void*)0);
            }
        }

        rc.UnbindAllBuffer();
    }

}
